package com.lf.web.service.system.module;

import com.lf.data.Cluster;
import com.lf.data.ClusterUtil;
import com.lf.data.search.Query;
import com.lf.data.search.Sort;
import com.lf.web.service.ServiceSupport;
import com.lf.web.service.system.extension.Extension;
import com.lf.web.service.system.extension.ExtensionDAO;
import com.lf.web.service.system.webnode.WebNode;
import com.lf.web.service.system.webnode.WebNodeDAO;
import org.apache.log4j.Logger;

import java.util.HashMap;
import java.util.List;

public class ModuleAddService extends ServiceSupport {

    private static final Logger LOGGER = Logger.getLogger(ModuleAddService.class);
    private ExtensionDAO extensiondao;
    private WebNodeDAO channeldao;

    public ModuleAddService() {
    }

    public void setExtensiondao(ExtensionDAO extensiondao) {
        this.extensiondao = extensiondao;
    }

    public void setChanneldao(WebNodeDAO channeldao) {
        this.channeldao = channeldao;
    }

    public String execute() {
        String type = form.getString("type");
        if ("extlist".equals(type)) {
            return extList();
        } else {
            return add();
        }
    }

    public String add() {
        Extension extension = new Extension();
        form.getCluster(extension);
        Cluster ext = extensiondao.findOne(extension);
        if (ext.isEmpty()) {
            LOGGER.error("错误插件：" + extension);
            return error(404);
        }

        Module module = new Module();
        module.put(Module.OPTION, new HashMap<String, Object>());
        Sort sort = new Sort();
        sort.desc(WebNode.INDEX);
        List<Cluster> channels = channeldao.find(null, null, sort);

        context.put("module", module);
        context.put("extension", extension);
        context.put("check", ClusterUtil.getCheck(Module.class));
        context.put("channels", channels);
        return "editview";
    }

    public String extList() {
        Query query = new Query();
        Extension ext = new Extension();
        query.eq(ext.STATUS, 1);
        List<Cluster> extlist = extensiondao.find(query, null, null);
        context.put("extlist", extlist);
        return "extlist";
    }
}
